/**
**	页面元数据操作模块，提供公共函数
**/

(function(){
//页面元数据对象，注册到window中，全局可用

var PageMetaObj = function(){

	//step 1: init stage:

	//系统中注册的buildin 类型
	this.types = ["TBaseInfo","TLinkDef","TTextLinkDef","TPicLinkDef","TPictureDef","TTextDef"];
	 
}

PageMetaObj.prototype = {
	// load buildin type def
init:function (pageMetaDefURL){
	var baseUrl = "/widget/";
	for(var i=0;i < types.length;i++){
		var tp = types[i];
		var url = baseUrl + tp + ".json";

	        typeMatrix[ types[i]] = fetchUrlContent(url);
	        console.log("loaded :" +  url);
	}
},
 
//step 2：load
loadPageMetaMetaDef:function(pageMetaDefURL){
	var meta = fetchUrlContent(pageMetaDefURL);
	pageMeta = JSON.parse(meta);
	return transToPageModeMeta(pageMeta);
}


/**
**	页面元数据模块共用函数库
**/

//深度copy对象函数，直接采用json-editor的js函数$extend

//动态装载json数据函数，返回指定url的json字符串
function fetchUrlContent(url){
	  var r = new XMLHttpRequest();
	  var ret = ""; 
	  r.open("GET", url, false);
	  r.onreadystatechange = function () {
		console.log("url:" + url);
	    if (r.readyState != 4) return; 
	    // Request succeeded
	    if(r.status === 200) {
	      var response;
	      try {
	        ret = r.responseText;
	        return ;
	      }
	      catch(e) {
	        window.console.log(e);
	        throw "Failed to parse external ref "+url;
	      }
	     }
	    // Request failed
	    else {
	      window.console.log(r);
	      throw "Failed to fetch ref via ajax- "+url;
	    }
	  };
	  r.send();
	  return ret;
      //throw "unkown error:"+ url;
}
 
} //end PageMetaObj prototype def

//register page meta to window obj
window.pagemata = PageMataObj;
})();
//end closure def
